/*
 * @Author: Lqq
 * @Date: 2025-07-08 12:24:45
 * @LastEditors: Lqq 46081704@qq.com
 * @LastEditTime: 2025-07-17 13:52:59
 * @FilePath: \questionnaire\src\common\api.ts
 * @Description:
 *
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved.
 */
// src/utils/api.ts
import axios, { AxiosRequestConfig, AxiosResponse } from "axios"
import { ElMessage } from "element-plus"

// ✅ 基地址
const BASE_URL = "http://111.33.30.253:18060/health/" // 你可以根据环境变量进行切换

// ✅ API_KEY
const API_KEY = "35B2B8EABC0EF3E664658C4A807698F48D568406B14B2C1311408A88D421C23A"

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    "Api-Key": API_KEY,
    "Content-Type": "application/json"
  }
})

// ✅ 响应拦截器：自动解包 data、错误统一处理
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data // 只返回 data 部分
  },
  (error) => {
    const msg = error?.response?.data?.message || error.message || "请求失败"
    ElMessage.error(msg)
    return Promise.reject(error)
  }
)

// ✅ 封装请求方法
export const get = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
  return instance.get(url, { params, ...config })
}

export const post = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return instance.post(url, data, config)
}

export const put = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return instance.put(url, data, config)
}

export const del = <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => {
  return instance.delete(url, config)
}
